using System;
using Gtk;
using System.Reflection;

namespace Serpis
{
	[System.ComponentModel.ToolboxItem(true)]
	public abstract partial class EntityListView : Gtk.Bin, IListView
	{
		
		protected Type modelType;
		protected Type viewType;

		public EntityListView(Type modelType, Type viewType)
		{
			this.Build ();
			
			this.modelType = modelType;
			this.viewType = viewType;
			
			label.LabelProp = "Nombre";
		}
			
		protected Label label {get {return pLabel;}}
		protected Entry entry {get {return pEntry;}}
		protected HBox hBoxFilter {get {return pHBoxFilter;}}
		protected MiTreeView miTreeView {get {return pMiTreeView;}}
	
	//	Obligamos a que todos los que hereden de esta clase, implementen el metodo getSql();
	protected abstract string getSql();
	
	//	Método que devuelve el valor de la primera columna
	protected virtual object getId()
	{
		long id = Convert.ToInt64(miTreeView.GetValue(0));
		return id;
	}
		
	protected void init()
	{
		string sql = getSql();
		miTreeView.Init(AppDbConnection.Instance.DbConnection, sql);
		
		miTreeView.Changed += delegate
		{
			raiseChanged();	
		};
	}
	
	public virtual void Refresh()
	{
//		string sql = string.Format(selectSQL, entryNombre.Text);
//		miTreeView.Refresh(sql);
	}
	public virtual bool HasSelected
	{
		get{return miTreeView.HasSelected;}
	}
		
	public virtual void New()
	{
		IPersister persister = PersisterFactory.NewPersister(modelType);	
		//	Creamos un objeto del typo 'modelType'
		object model = Activator.CreateInstance(modelType);
		show(model, persister);
	}
		
	public virtual void Edit()
	{
		IPersister persister = PersisterFactory.NewPersister(modelType);
		object model = persister.Load(modelType, getId());
		show(model, persister);
	}
		
	protected virtual void show(object model, IPersister persister)
	{
		IEntityView view = (IEntityView)Activator.CreateInstance(viewType);
		
		Controller controller = new Controller(model, view);
		controller.Refresh();
		
		view.SaveAction.Activated += delegate 
		{
			controller.Update();
			view.Destroy();
			persister.Save(model);
			miTreeView.Refresh();
		};		
	}
	
	public virtual void Delete()
	{
		MessageDialog messageDialog = new MessageDialog(null, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, "Desees eliminar el registro");
		//	ponemos como titulo, el resultado de ejecutar el metodo de extensión GetLabel
		messageDialog.Title = modelType.GetLabel();
		int response = messageDialog.Run();
		messageDialog.Destroy();
		if(response != (int)ResponseType.Yes)
			return;
		
		IPersister persister = PersisterFactory.NewPersister(modelType);
		persister.Delete(modelType, getId());			
		miTreeView.Refresh();
	}
					
	// Evento para detectar el cambio de seleccion ->Esta implementado en MiBin
	protected virtual void raiseChanged()
	{
		if(Changed != null)
			Changed(this, EventArgs.Empty);
	}
					
	//	Parte del codigo del evento
	public event EventHandler Changed;
	}
}
